package de.ret_world.openrpgstudio.editor.gui;

import buoy.event.CommandEvent;
import buoy.widget.BButton;
import buoy.widget.LayoutInfo;
import buoy.widget.RowContainer;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.util.logging.Level;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.Icon;
import org.apache.log4j.Logger;
import org.newdawn.easyogg.OggClip;

/**
 * With this widget you can preview a sound effect or a music clip. It contains
 * of two control buttons (start and stop).
 *
 * @author Emu
 */
public class AudioPreviewWidget extends RowContainer {

    private BButton btnStart;
    private BButton btnStop;
    private Clip audioClip;
    private AudioInputStream ais;
    private OggClip sound;
    private boolean continouus;
    public static Icon iconStart;
    public static Icon iconStop;

    public AudioPreviewWidget(Path audio, boolean continouus) {
        this(continouus);
        setAudio(audio);
    }

    public AudioPreviewWidget(boolean continouus) {
        this.continouus = continouus;

        btnStart = new BButton(iconStart);
        btnStart.addEventLink(CommandEvent.class, this, "play");
        add(btnStart, new LayoutInfo(LayoutInfo.WEST, LayoutInfo.NONE));
        btnStop = new BButton(iconStop);
        btnStop.addEventLink(CommandEvent.class, this, "stop");
        add(btnStop, new LayoutInfo(LayoutInfo.WEST, LayoutInfo.NONE));
    }

    public void setAudio(Path audio) {
        if (audio.endsWith(".ogg") || audio.endsWith(".OGG") || continouus) {
            try {
                sound = new OggClip(new FileInputStream(audio.toFile()));
            } catch (IOException ex) {
                Logger.getLogger(AudioPreviewWidget.class).error(ex);
            }
        } else {
            try {
                audioClip = AudioSystem.getClip();
                ais = AudioSystem.getAudioInputStream(audio.toFile());
                audioClip.open(ais);

            } catch (UnsupportedAudioFileException | LineUnavailableException | IOException ex) {
                Logger.getLogger(AudioPreviewWidget.class).error(ex);
            }
        }
    }

    private void play() {
        if (audioClip != null) {
            audioClip.flush();
            audioClip.setFramePosition(0);
//            if (continouus) {
//                audioClip.loop(Clip.LOOP_CONTINUOUSLY);
//            }
            audioClip.start();
        }

        if (sound != null) {
            sound.stop();
            sound.play();
        }
    }

    private void stop() {
        if (audioClip != null) {
            audioClip.stop();
        }

        if (sound != null) {
            sound.stop();
        }
    }
}
